<script setup>
import $ from 'jquery'
import { onMounted,ref } from 'vue';

import kscreenshot from 'kscreenshot'

onMounted(()=>{
    
    const btn = document.querySelector("#btn");
    btn.addEventListener("click", handleCopyImg, false);
    handleCopyImg();
    clipboard2Img();
});


function handleCopyImg() {
  const selection = window.getSelection();
  // 清除选中
  if (selection.rangeCount > 0) selection.removeAllRanges();
  // https://developer.mozilla.org/zh-CN/docs/Web/API/Document/queryCommandSupported
  if(!document.queryCommandSupported('copy')) return alert('浏览器暂不支持复制命令');
  // 创建range区域
  const range = document.createRange(); 
  const testImg = document.querySelector("#testImg");
  range.selectNode(testImg);
  selection.addRange(range);
  document.execCommand("copy");
  selection.removeAllRanges();
}
var msgcontent = ref(null)
function mouseCutImg(){

      new kscreenshot({
        key: 65,
        needDownload: false,
        endCB(e) { //截图成功回调
          console.log(e)
          msgcontent.value =e ;
        },
        cancelCB(e) { //截图失败回调
          console.log(e)
        }
      }).startScreenShot()
 
}

function clipboard2Img(){
    $("#textareaid").bind("paste", function(e){

        var items = (e.clipboardData || e.originalEvent.clipboardData).items;
        console.log(JSON.stringify(items)); // will give you the mime types

        for (index in items) 
        {
            var item = items[index];
            if (item.kind === 'file') 
            {
                var blob = item.getAsFile();
                var reader = new FileReader();

                reader.onload = function(event){

                    // show image in string 
                    console.log(event.target.result);

                    // make a clone in textareaid2 
                    $("#textareaid2").append("<img src='" + event.target.result + "'>");
                }; // data url!
                reader.readAsDataURL(blob);
            } 
            else
            {
                return true;
            }
        }
    });   // end bind
}


</script>

<template>
    <div>
        <img id="testImg" src="/assets/images/avatar01.jpg" alt="img">
        <button id="btn">copy</button>
        <button @click="mouseCutImg()">Cut</button>
        <img :src="msgcontent" alt="ended pic" />

        <div id="textareaid" style="margin:10px 0px;min-width:200px;min-height:200px;border:1px solid #ccc;" contenteditable="true" placeholder="test paste">
        </div>

        <div id="textareaid2"></div>
    </div>
</template>